$(document).ready(function(){
	var currentPage = 1;
	var pageSize = 10;
	var token = $.zui.store.get("token");
	var userId = $.zui.store.get("userId");
	
	var queryListFun = function(){
		//获取列表数据
		var queryListUrl = adminQueryUrl + areaService + queryArea;
		
		var param = "";
		//搜索参数
		if ($("#queryAreaCode").val()!=''){
			param += "&AreaCode="+$("#queryAreaCode").val();
		}
		if ($("#queryAreaNameLike").val()!=''){
			param += "&AreaNameLike="+$("#queryAreaNameLike").val();
		}
		if (currentPage>0){
			param += "&currentPage="+(currentPage-1);
		}
		param += "&pageSize="+pageSize;
		param += "&currentPage="+(currentPage-1);
		
		console.log('queryListUrl='+queryListUrl);
		console.log('token='+token+",userId="+userId);
		console.log('param='+param);
		$.ajax({
			url:queryListUrl,
			type:'post',
			beforeSend:function(xhr){
				xhr.setRequestHeader("token",token);
				xhr.setRequestHeader("userId",userId);
			},
			header:{"token":token,"userId":userId},
			data:param,
			dataType:"JSON",
			success:function(result){
				console.log(result.success);
				console.log(result.pageList);
				if (result.success== '1'){
					
					$('#listDataGrid').empty();
					$('#listDataGrid').data('zui.datagrid',null);
					$('#listPager').empty();
					$('#listPager').data('zui.pager',null);
					
					$('#listDataGrid').datagrid({
						checkable: true,
					    checkByClickRow: true,
					    selectable: true,
					    dataSource: {
					        cols:[
					            {name: 'areaCode', label: '地区编码', width: 132},
					            {name: 'areaName', label: '地区名称', width: 134},
					            {name: 'areaParentName', label: '上级地区名称', width: 109},
					            {name: 'areaSortCode', label: '排序码', width: 109},
					            {name: 'DESCRIPTION', label: '描述', width: 287},
					            {name: 'AREA_ID', label: '描述', hidden:true}
					        ],
					        cache:false,
					        array:result.pageList
					    }
					 
					});	
					
					// 手动进行初始化
					$('#listPager').pager({
					    page: currentPage,
					    recPerPage:pageSize,
					    elements:['first_icon', 'prev_icon', 'pages', 'next_icon', 'last_icon', 'total_text','size_menu','goto'],
					    pageSizeOptions:[5,10,20,30,50,100],
					    recTotal: result.pageTotal
					});
				}
				else {
					new $.zui.Messager(result.msg, {
					    type: 'warning', // 定义颜色主题
					    placement: 'center' // 定义显示位置
					}).show();
				}
			},
			error:function(result){
				new $.zui.Messager('系统繁忙,请稍候再试!', {
				    type: 'warning', // 定义颜色主题
				    placement: 'center' // 定义显示位置
				}).show();
			}
		});
	};
	//调起查询数据
	queryListFun();
	//查询
	$("#searchBtn").click(function(){
		queryListFun();
	});
	//监听分页，修改当前页，条数
	$('#listPager').on('onPageChange', function(e, state, oldState) {
		currentPage = state.page;
		pageSize = state.recPerPage;
		queryListFun();
	});
	
	
	//初始化添加
	$("#addBtn").click(function(){
		//获取上级菜单列表
		var url = adminQueryUrl + areaService +queryArea ;
		var param = '';//请求到列表页面
		$("#addForm")[0].reset();
		console.log(url+param);
		$.ajax({
			url:url,
			type:'post',
			dataType:'JSON',
			beforeSend:function(xhr){//设置请求头信息
				xhr.setRequestHeader("token",token);
				xhr.setRequestHeader("userId",userId);
			},
			header:{'token':token,'userId':userId},
			data:param,
			success:function(data){
				console.log('data='+data.pageList[0]);
				if (data.success=='1'){
					$("#addAreaParentCode").empty();
					$("#addAreaParentCode").append('<option value="0">请选择</option>');
					$.each(data.pageList, function(i, item){ 
						if(item.AreaParentId == null)
						{
							$("#addAreaParentCode").append("<option value='"+item.areaCode+"'>"+item.areaName+"</option>");
						}
						
					});  
				}
			},
			error:function(e){
				new $.zui.Messager('系统繁忙,请稍候再试!', {
				    type: 'warning',
				    placement:'center'
				}).show();
			}
		});
	});
	

	
	$("#addSaveBtn").click(function(){
			var validAreaNameUrl = adminQueryUrl + areaService + validAreaName ;
			var validAreaCodeUrl = adminQueryUrl + areaService + validAreaCode ;
			console.log("validAreaNameUrl"+validAreaNameUrl);
			console.log("validAreaCodeUrl"+validAreaCodeUrl);
			$("#addForm").validate({
				rules:{
					addAreaCode:{
						"required":true,
						"remote":{
							url:validAreaCodeUrl,
							type:'post',
							beforeSend:function(xhr){//设置请求头信息
								xhr.setRequestHeader("token",token);
								xhr.setRequestHeader("userId",userId);
							},
							header:{'token':token,'userId':userId},
							dataType:'json',
							data:{
								'addAreaCode':function(){
									return $("#addAreaCode").val();
								}
							}
						}
					},
					addAreaName:{
						"required":true,
						"remote":{
							url:validAreaNameUrl,
							type:'post',
							beforeSend:function(xhr){//设置请求头信息
								xhr.setRequestHeader("token",token);
								xhr.setRequestHeader("userId",userId);
							},
							header:{'token':token,'userId':userId},
							dataType:'json',
							data:{
								'addAreaName':function(){
									return $("#addAreaName").val();
								}
							}
						}
					},
					addDescription:"required",
					addSortNo:{
						"required":true,
						"digits":true
					},
					
				},
				messages:{
					addAreaCode:{
						"required":"请输入菜单编码！",
						"remote":"该菜单编码已经存在"
					},
					addAreaName:{
						"required":"请输入菜单名称！",
						"remote":"该菜单名称已经存在"
					},
					addDescription: "请输入描述信息！",
					addSortNo: {
						"required":"请输入排序码！",
						"digits":"只能输入数字！"
					},
				},
				submitHandler:function(form){
					console.log("xx:"+adminQueryUrl +  areaService + addArea);
					
					$.ajax({
						url:adminQueryUrl + areaService + addArea ,
						type:'post',
						dataType:'JSON',
						beforeSend:function(xhr){//设置请求头信息
							xhr.setRequestHeader("token",token);
							xhr.setRequestHeader("userId",userId);
						},
						header:{'token':token,'userId':userId},
						data:$(form).serialize(),
						success:function(data){
							console.log('data='+data);
							if (data.success == '1') {
			                	new $.zui.Messager('添加成功!', {
			    				    type: 'success',
			    				    placement:'center'
			    				}).show();
			                	queryListFun();
			                	$('#addModal').modal('hide', 'fit');
			                }
			                else{
			                	new $.zui.Messager(data.msg, {
			    				    type: 'warning',
			    				    placement:'center'
			    				}).show();
			                }
						},
						error:function(e){
							new $.zui.Messager('系统繁忙,请稍候再试!', {
		    				    type: 'warning',
		    				    placement:'center'
		    				}).show();
						}
					});
				}
			});	
	    });
	
	$("#updateBtn").click(function(){
		// 获取数据表格实例
		var listDataGrid = $('#listDataGrid').data('zui.datagrid');
		// 获取当前已选中的行数据项
		var selectedItems = listDataGrid.getCheckItems();
		if (selectedItems.length == 0) {
			new $.zui.Messager('请选择要修改的记录', {
			    type: 'warning',
			    placement:'center'
			}).show();
		}
		else if (selectedItems.length > 1) {
			new $.zui.Messager('请只选择一条要修改的记录', {
			    type: 'warning',
			    placement:'center'
			}).show();
		}
		else {
			$("#updateForm")[0].reset();
			var url = adminQueryUrl + areaService +initUpdateMethod;
			var param = 'AreaId='+selectedItems[0].AREA_ID;//请求到列表页面
			console.log('param='+param);
			$.ajax({
				url:url,
				type:'post',
				dataType:'JSON',
				beforeSend:function(xhr){//设置请求头信息
					xhr.setRequestHeader("token",token);
					xhr.setRequestHeader("userId",userId);
				},
				headers:{'token':token,'userId':userId},
				data:param,
				success:function(data){
					console.log('data='+data);
					if (data.success=='1'){
						$('#updateModal').modal('show', 'fit');
						$("#updateAreaParentCode").empty();
						$("#updateAreaParentCode").append('<option value="0">请选择</option>');
						$.each(data.areaParentList, function(i, item){   
							
							if (data.areaMap.areaParentCode == item.areaCode){
								$("#updateAreaParentCode").append("<option value='"+item.areaCode+"' selected='selected'>"+item.areaName+"</option>");
							}
							else {
								$("#updateAreaParentCode").append("<option value='"+item.areaCode+"'>"+item.areaName+"</option>");
							}
						});  
						$("#updateAreaCode").val(data.areaMap.areaCode);
						$("#updateAreaName").val(data.areaMap.areaName);
						$("#updateSortCode").val(data.areaMap.areaSortCode);
						$("#updateDescription").val(data.areaMap.DESCRIPTION);
						$("#updateAreaId").val(data.areaMap.AREA_ID);
					}
				},
				error:function(e){
					new $.zui.Messager('系统繁忙,请稍候再试!', {
					    type: 'warning',
					    placement:'center'
					}).show();
				}
			});
		}
	});
	//修改保存
	$("#updateSave").click(function(){
	
		var validAreaNameUrl = adminQueryUrl + areaService + validAreaName ;
		var validAreaCodeUrl = adminQueryUrl + areaService + validAreaCode ;
		console.log("validAreaNameUrl"+validAreaNameUrl);
		console.log("validAreaCodeUrl"+validAreaCodeUrl);
		$("#updateForm").validate({
			rules:{
				updateAreaCode:{
					"required":true,
					"remote":{
						url:validAreaCodeUrl,
						type:'post',
						beforeSend:function(xhr){//设置请求头信息
							xhr.setRequestHeader("token",token);
							xhr.setRequestHeader("userId",userId);
						},
						header:{'token':token,'userId':userId},
						dataType:'json',
						data:{
						'addAreaCode':function(){
							return $("#updateAreaCode").val();
						},
						'excludeAreaId':function(){
							return $("#updateAreaId").val();
						}
						}
					}
				},
				updateAreaName:{
					"required":true,
					"remote":{
						url:validAreaNameUrl,
						type:'post',
						beforeSend:function(xhr){//设置请求头信息
							xhr.setRequestHeader("token",token);
							xhr.setRequestHeader("userId",userId);
						},
						header:{'token':token,'userId':userId},
						dataType:'json',
						data:{
							'addAreaName':function(){
								return $("#updateAreaName").val();
							},
							'excludeAreaId':function(){
								return $("#updateAreaId").val();
							}
						}
					}
				},
				addDescription:"required",
				addSortNo:{
					"required":true,
					"digits":true
				},
				
			},
			messages:{
				updateAreaCode:{
					"required":"请输入菜单编码！",
					"remote":"该菜单编码已经存在"
				},
				updateAreaName:{
					"required":"请输入菜单名称！",
					"remote":"该菜单名称已经存在"
				},
				addDescription: "请输入描述信息！",
				addSortNo: {
					"required":"请输入排序码！",
					"digits":"只能输入数字！"
				},
			},
			submitHandler:function(form){
				var saveUrl = adminQueryUrl + areaService + saveUpdate;
				$.ajax({
					url:saveUrl,
					type:'post',
					dataType:'JSON',
					beforeSend:function(xhr){//设置请求头信息
						xhr.setRequestHeader("token",token);
						xhr.setRequestHeader("userId",userId);
					},
					header:{'token':token,'userId':userId},
					data:$(form).serialize(),
					success:function(data){
						console.log('data='+data);
						if (data.success == '1') {
		                	new $.zui.Messager('修改成功!', {
		    				    type: 'success',
		    				    placement:'center'
		    				}).show();
		                	queryListFun();
		                	$('#updateModal').modal('hide', 'fit');
		                	queryAreaListFun();
		                }
		                else{
		                	new $.zui.Messager(data.msg, {
		    				    type: 'warning',
		    				    placement:'center'
		    				}).show();
		                }
					},
					error:function(e){
						new $.zui.Messager('系统繁忙,请稍候再试!', {
	    				    type: 'warning',
	    				    placement:'center'
	    				}).show();
					}
				});
			}
		});
	});
	//显示删除确认框
	$("#deleteBtn").click(function(){
		// 获取数据表格实例
		var listDataGrid = $('#listDataGrid').data('zui.datagrid');
		// 获取当前已选中的行数据项
		var selectedItems = listDataGrid.getCheckItems();
		if (selectedItems.length == 0) {
			new $.zui.Messager('请选择要删除的记录', {
			    type: 'warning',
			    placement:'center'
			}).show();
		}
		else if (selectedItems.length > 1) {
			new $.zui.Messager('请只选择一条要删除的记录', {
			    type: 'warning',
			    placement:'center'
			}).show();
		}
		else {
			$('#deleteModal').modal('show', 'fit');
		}
	});
	//删除菜单
	$("#deleteAreaBtn").click(function(){
		// 获取数据表格实例
		var listDataGrid = $('#listDataGrid').data('zui.datagrid');
		// 获取当前已选中的行数据项
		var selectedItems = listDataGrid.getCheckItems();
		var url = adminQueryUrl + areaService + deleteMethod;
		var param = 'areaId='+selectedItems[0].AREA_ID;//请求到列表页面
		console.log('url='+url);
		console.log('param2='+param);
		$.ajax({
			url:url,
			type:'post',
			dataType:'JSON',
			beforeSend:function(xhr){//设置请求头信息
				xhr.setRequestHeader("token",token);
				xhr.setRequestHeader("userId",userId);
			},
			header:{'token':token,'userId':userId},
			data:param,
			success:function(data){
				console.log('data='+data);
				$('#deleteModal').modal('hide', 'fit');
				if (data.success=='1'){
	                	new $.zui.Messager('删除成功!', {
	    				    type: 'success',
	    				    placement:'center'
	    				}).show();
	                	queryListFun();
				}
                else{
                	new $.zui.Messager(data.msg, {
    				    type: 'warning',
    				    placement:'center'
    				}).show();
				}
			},
			error:function(e){
				new $.zui.Messager('系统繁忙,请稍候再试!', {
				    type: 'warning',
				    placement:'center'
				}).show();
			}
		});
	});
	//初始化详情
	$("#detailBtn").click(function(){
		// 获取数据表格实例
		var listDataGrid = $('#listDataGrid').data('zui.datagrid');
		// 获取当前已选中的行数据项
		var selectedItems = listDataGrid.getCheckItems();
		if (selectedItems.length == 0) {
			new $.zui.Messager('请选择要查看的记录', {
			    type: 'warning',
			    placement:'center'
			}).show();
		}
		else if (selectedItems.length > 1) {
			new $.zui.Messager('请只选择一条要查看的记录', {
			    type: 'warning',
			    placement:'center'
			}).show();
		}
		else {
			$("#detailForm")[0].reset();
			var url = adminQueryUrl + areaService + detailMethod;
			var param = 'areaId='+selectedItems[0].AREA_ID;//请求到列表页面
			console.log('param='+param);
			$.ajax({
				url:url,
				type:'post',
				dataType:'JSON',
				beforeSend:function(xhr){//设置请求头信息
					xhr.setRequestHeader("token",token);
					xhr.setRequestHeader("userId",userId);
				},
				header:{'token':token,'userId':userId},
				data:param,
				success:function(data){
					console.log('data='+data);
					if (data.success=='1'){
						$('#detailModal').modal('show', 'fit');
						
						$("#detailAreaName").html(data.areaMap.areaName);
						$("#detailAreaCode").html(data.areaMap.areaCode);
						$("#detailParentName").html(data.areaMap.areaParentName);
						$("#detailSortNo").html(data.areaMap.areaSortCode);
						$("#detailOprDate").html(data.areaMap.oprDate);
						$("#detailDescription").html(data.areaMap.DESCRIPTION);
					}
				},
				error:function(e){
					new $.zui.Messager('系统繁忙,请稍候再试!', {
					    type: 'warning',
					    placement:'center'
					}).show();
				}
			});
		}
	});
});